package com.ncdnapp.config;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.datasource.FlexDataSource;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.core.table.DynamicTableProcessor;
import com.mybatisflex.core.table.TableManager;
import com.mybatisflex.solon.ConfigurationCustomizer;
import com.mybatisflex.solon.MyBatisFlexCustomizer;
import com.ncdnapp.config.db.BaseDataSource;
import com.ncdnapp.config.db.DynamicTableHandle;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.bean.LifecycleBean;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@Slf4j
public class DbConfig implements MyBatisFlexCustomizer, ConfigurationCustomizer, LifecycleBean {
    @Inject
    private List<BaseDataSource> baseDataSourceList;
    @Inject
    private List<DynamicTableHandle> dynamicTableHandleList;


    @Override
    public void start() throws Throwable {
        //动态数据源
        FlexGlobalConfig flexGlobalConfig = FlexGlobalConfig.getDefaultConfig();
        FlexDataSource flexDataSource = flexGlobalConfig.getDataSource();
        if (!Utils.isEmpty(this.baseDataSourceList)) {
            baseDataSourceList.forEach(d -> {
                flexDataSource.addDataSource(d.getDataSourceName(), d.getDataSource());
            });
        }
        //动态表
        if (!Utils.isEmpty(dynamicTableHandleList)) {
            Map<String, DynamicTableHandle> dynamicTableHandleMap = dynamicTableHandleList.stream()
                    .collect(Collectors.toMap(DynamicTableHandle::getSourceTableName, l -> l, (v1, v2) -> v2));
            TableManager.setDynamicTableProcessor(new DynamicTableProcessor() {
                @Override
                public String process(String sourceTableName) {
                    DynamicTableHandle dynamicTableHandle = dynamicTableHandleMap.get(sourceTableName);
                    if (dynamicTableHandle != null) {
                        return dynamicTableHandle.handle(sourceTableName);
                    }
                    return sourceTableName;
                }
            });
        }
    }

    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {
        flexGlobalConfig.setPrintBanner(false);
        AuditManager.setAuditEnable(true);

        //设置 SQL 审计收集器
        AuditManager.setMessageCollector(auditMessage -> {
            if (log.isDebugEnabled()) {
                log.debug("{},{}ms", auditMessage.getFullSql(), auditMessage.getElapsedTime());
            }
        });
    }

    @Override
    public void customize(FlexConfiguration flexConfiguration) {

    }
}
